package ServerConnection;

import Message.AccountAddFriendInfo;
import Message.AccountSendMessageInfo;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;


/**该类是存储客户端发送的聊天记录到数据库的线程类*/
public class ThreadHandleSendMessage implements Runnable{
    Socket socket = null;
    AccountSendMessageInfo accountSendMessageInfo;
    boolean res;
    DatabaseServer databaseServer;

    public ThreadHandleSendMessage(Socket socket, DatabaseServer databaseServer) {
        super();
        this.socket = socket;
        this.databaseServer = databaseServer;
    }

    @Override
    public void run() {
        System.out.println("收到用户的登录请求，正在处理");
        //获取从客户端得到的消息，并且执行了消息。
        try{
            InputStream inputStream = socket.getInputStream();
            ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
            accountSendMessageInfo = (AccountSendMessageInfo) objectInputStream.readObject();

            String userIdInDatabaseFrom = accountSendMessageInfo.getUserIdInDatabaseFrom();
            String userIdInDatabaseTo = accountSendMessageInfo.getUserIdInDatabaseTo();
            String messageInfo = accountSendMessageInfo.getMessageInfo();
            Timestamp time = accountSendMessageInfo.getTime();
            String sql = String.format("INSERT INTO Message(time, userIdInDatabaseFrom, " +
                            "userIdInDatabaseTo, message) VALUE ('%s','%s','%s','%s');",
                    time, userIdInDatabaseFrom, userIdInDatabaseTo, messageInfo);
            res = databaseServer.doExecute(sql);
            System.out.println("插入聊天记录结果为："+res);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(String.valueOf(res).getBytes(StandardCharsets.UTF_8));

            inputStream.close();
            objectInputStream.close();
            outputStream.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
